﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Dynamic_UI_Framework
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="U">dapterinstance</typeparam>
    /// <typeparam name="T">target</typeparam>
    public abstract class AdapterBase<U, T> : IAdapter where T : class where U: IVisual
    {
        public virtual U DefaultBuild(string name)
        {
            T target =  Activator.CreateInstance<T>();
            if(target == null)
                throw new Exception("target == null");


            return Initialize(target, name);
        }

        public virtual U Initialize(T target, string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("visualLayoutName");
            }

            U  source = this.Create();
            source.Name = name;

            SetObservableRegionOnHostingControl(source, target);

            this.Adapt(source, target);
            return source;

        }

        protected abstract void Adapt(U codon, T target);

        protected abstract U Create();

        private static void SetObservableRegionOnHostingControl(U bench, T target)
        {
            DependencyObject targetElement = target as DependencyObject;

            if (targetElement != null)
            {
                // Set the region as a dependency property on the control hosting the region
                // Because we are using an observable region, the hosting control can detect that the
                // region has actually been created. This is an ideal moment to hook up custom behaviors
                //RegionManager.GetObservableRegion(targetElement).Value = visualLayout;
            }
        }


        IVisual IAdapter.DefaultBuild(string name)
        {
            return this.DefaultBuild(name);
        }

        IVisual IAdapter.Initialize(object target, string name)
        {
            T castedObject = target as T;
            if (castedObject == null)
                throw new Exception("castedObject == null");

            return this.Initialize(castedObject, name);
        }
    }
}
